package com.syt.service.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.syt.service.pojo.PhoneUser;
import com.syt.service.service.PhoneUserService;
import com.syt.service.service.TokenService;
import com.syt.service.util.LoginRequired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author ：syt
 * @date ：Created in 2019-10-06 20:54
 * @description：用户 登录 注册类  验证码等会加
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    PhoneUserService userService;
    @Autowired
    TokenService tokenService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 登录验证
     * @param user
     * @return
     */
    @PostMapping("login")
    public Object login(@RequestBody PhoneUser user) {
        JSONObject jsonObject = new JSONObject();
        PhoneUser userForBase = userService.findUserByName(user.getUserName());
        if (userForBase == null) {
            jsonObject.put("message", "用户不存在");
            return jsonObject;
        }
        if (!userForBase.getUserPassword().equals(user.getUserPassword())) {
            jsonObject.put("message", "登录失败，密码出错");
            return jsonObject;
        }
        String token = tokenService.getToken(userForBase);
        jsonObject.put("token", token);
        jsonObject.put("message", "登录成功");
        return jsonObject;
    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    @GetMapping("logout")
    @LoginRequired
    public Object logout(@RequestHeader String token, @RequestAttribute String userId) {
        JSONObject jsonObject = new JSONObject();
        tokenService.cleanToken(token);
        jsonObject.put("userId", userId);
        return jsonObject;
    }

    /**
     * 注册, 等待完工 校验部分
     * @param user
     * @return
     */
    @PostMapping("register")
    public Object register(@RequestBody PhoneUser user) {
        JSONObject jsonObject = new JSONObject();
        if (user.getUserName().length() < 4 && user.getUserPassword().length() < 5) {
            jsonObject.put("message", "用户名,密码不合适");
            return jsonObject;
        }
        PhoneUser userForBase = userService.findUserByName(user.getUserName());
        if (userForBase != null) {
            jsonObject.put("message", "用户名已经存在了");
            return jsonObject;
        }
        jsonObject.put("uid", userService.setUser(user));
        jsonObject.put("token", tokenService.getToken(userService.findUserByName(user.getUserName())));
        return jsonObject;
    }

    /**
     * 管理 员登录界面
     * @return
     */
    @GetMapping("admin/login")
    public ModelAndView adminLogin() {
        ModelAndView view = new ModelAndView("login");
        return view;
    }
}
